<script lang="ts" setup>
// vue
import { ref, watch, computed } from 'vue'
// type
import type { goods } from '@/types/category'
import type { InputNumberBoxEvent } from '@/components/vk-data-input-number-box/vk-data-input-number-box'
// api
import { cartEditAPI } from '@/services/cart'

// 弹出层组件 ref
const popup = ref<{
  // 指定方法
  // 打开方法
  open: (type?: UniHelper.UniPopupType) => void
  // 关闭方法
  close: () => void
}>()

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// 本地cartList
const localCartList = ref<goods[]>([])
// 通知父组件更新cartList
const emit = defineEmits(['update:categoryCartList', 'pay'])

/**
 * 数量改变
 */
const onCountChange = async (ev: InputNumberBoxEvent) => {
  // index: skuId, value: 购买数量
  const { index, value } = ev
  // 判断cartGoodsList中是否有该商品
  const newGoods = localCartList.value.find(
    (item) => item.singleSkuId === index,
  )
  // 如果有，则更新数量
  if (newGoods) {
    // 更新数量
    newGoods.buyCount = value
    emit('update:categoryCartList', { skuId: index, count: value })
  }
}

/**
 * 去付款
 */
const onPayClick = () => {
  // 判断是否有商品
  if (localCartList.value.length === 0) {
    uni.showToast({
      title: '请选择商品',
      icon: 'none',
    })
    return
  }
  emit('pay')
  // 关闭sku弹窗
  close()
}

/**
 * 计算 cartGoodsList 总价
 */
const totalPrice = computed(() => {
  let total = 0
  for (let i = 0; i < localCartList.value.length; i++) {
    const goods = localCartList.value[i]
    const goodsPrice = parseFloat(goods.price)
    total += goodsPrice * goods.buyCount
  }
  return total
})

/**
 * 计算 cartGoodsList 总件数
 */
const totalCount = computed(() => {
  let total = 0
  for (let i = 0; i < localCartList.value.length; i++) {
    const goods = localCartList.value[i]
    total += goods.buyCount
  }
  return total
})
/**
 * 打开弹窗
 */
const open = (cartList: goods[]) => {
  localCartList.value = []
  // 赋值本地cartList
  localCartList.value = cartList.map((item) => {
    return {
      ...item,
      buyCount: item.buyCount || 0,
    }
  })
  // 打开弹出层
  popup.value?.open()
}
/**
 * 关闭弹窗
 */
const close = () => {
  // 关闭弹出层
  popup.value?.close()
}
/**
 * 暴露给父组件的方法
 */
defineExpose({
  open,
})
</script>

<template>
  <uni-popup ref="popup" type="bottom" background-color="#fff">
    <view class="cart-panel">
      <!-- 关闭按钮 -->
      <text class="close icon-close" @click="close"></text>
      <!-- 标题 -->
      <view class="title">共{{ totalCount }}件商品</view>
      <!-- 内容 -->

      <scroll-view class="content" scroll-y>
        <view class="item" v-for="(item, index) in localCartList" :key="index">
          <view class="goods-item" v-if="item.buyCount > 0">
            <!-- 商品名称 -->
            <view class="goods-info">
              <text class="name">{{ item.name }}</text>
              <text class="sku-text"> {{ item.skuText }} </text>
            </view>
            <!-- 价格和数量 -->
            <view class="price-and-count">
              <text class="price">￥{{ item.price }}</text>
              <view class="count">
                <vk-data-input-number-box
                  v-model="item.buyCount"
                  :min="0"
                  :max="item.stock"
                  :index="item.singleSkuId"
                  :disabledInput="true"
                  @change="onCountChange"
                />
              </view>
            </view>
          </view>
        </view>
        <view>
          <view
            class="toolbar"
            :style="  { paddingBottom: safeAreaInsets!.bottom + 'px' } "
          >
            <text class="text">合计:</text>
            <text class="amount">¥{{ totalPrice.toFixed(2) }}</text>
            <view class="button-grounp">
              <view class="button payment-button" @click="onPayClick">
                去付款
              </view>
            </view>
          </view>
          <!-- 底部占位空盒子 -->
          <view class="toolbar-height"></view>
        </view>
      </scroll-view>
    </view>
  </uni-popup>
</template>

<style lang="scss">
.cart-panel {
  padding: 0 30rpx;
  border-radius: 10rpx 10rpx 0 0;
  position: relative;
  background-color: #fff;
  height: 50vh; // 设置弹窗高度为屏幕高度的一半
}

.title {
  line-height: 1;
  padding: 30rpx 0;
  text-align: center;
  font-size: 30rpx;
  font-weight: normal;
  border-bottom: 1rpx solid #ddd;
  color: #444;
}

.close {
  position: absolute;
  right: 24rpx;
  top: 24rpx;
}

.content {
  display: flex;
  flex-direction: column;
  padding: 20rpx 20rpx 100rpx 20rpx;
  height: 100%;
  overflow: hidden;

  .item {
    .goods-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      // 下划线
      border-bottom: 1rpx solid #ddd;
      // 下内边距
      padding: 15rpx 0 15rpx 0;
      width: 100%;
    }

    /* 商品名称 */
    .goods-info {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-start;

      color: #333;

      .name {
        // 下外边距
        margin-bottom: 10rpx;
        font-size: 30rpx;
        color: #444;
      }
      .sku-text {
        line-height: 1.8;
        padding: 0 15rpx;
        margin-top: 6rpx;
        font-size: 24rpx;
        align-self: flex-start;
        border-radius: 4rpx;
        color: #888;
        background-color: #f7f7f8;
      }
    }

    /* 价格-数量 */
    .price-and-count {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 50%;

      /* 价格 */
      .price {
        font-size: 28rpx;
        color: #cf4444;
        margin-right: 20rpx;
      }
    }
  }
}
</style>
